package com.toplabs.unashu.aspect;

import com.toplabs.unashu.annotation.ControllerEndpoint;
import com.toplabs.unashu.common.response.CommonResponse;
import com.toplabs.unashu.common.utils.IPUtils;
import com.toplabs.unashu.entity.Log;
import com.toplabs.unashu.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LogAspect {

    private final LogService logService;

    public LogAspect(LogService logService) {
        this.logService = logService;
    }

    @Pointcut("@annotation(com.toplabs.unashu.annotation.ControllerEndpoint)")
    public void log() {
    }

    @Before("log()")
    public void doBefore() {
        log.info("----------doBefore----------");
    }

    @After("log()")
    public void doAfter() {
        log.info("----------doAfter----------");
    }

    @Around("log()")
    public Object saveSysLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Log sysLog = new Log();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;

        HttpServletRequest request = attributes.getRequest();
        //开始时间
        long startTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取注解
        ControllerEndpoint controllerEndpoint = method.getAnnotation(ControllerEndpoint.class);
        if (controllerEndpoint != null) {
            String operation = controllerEndpoint.operation();
            // 注解上的操作描述
            sysLog.setOperation(operation);
        }

        // 请求的参数
        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        sysLog.setParams("paramName:" + Arrays.toString(paramNames) + ",args:" + Arrays.toString(args));

        // 请求的IP
        String ipAddr = IPUtils.getIpAddr(request);
        sysLog.setIp(ipAddr);

        // 地理位置
        sysLog.setLocation(IPUtils.getCityInfo(ipAddr));

        // 请求的url
        String url = request.getRequestURL().toString();
        sysLog.setUrl(url);

        // 执行目标方法
        Object result = joinPoint.proceed();

        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "()";
        sysLog.setMethod(classMethod);

        // 执行耗时
        sysLog.setTime(System.currentTimeMillis() - startTime);

        log.info("Result: {}", sysLog);
        logService.saveLog(sysLog);
        return result;
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(CommonResponse<?> result) {
        log.info("CommonResponse: {}", result);
    }
}
